package com.qf.mao.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.mao.entity.RespBean;
import com.qf.mao.service.UserService;
import com.qf.mao.utils.CommonsUtils;
import com.qf.mao.utils.VerificationCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author 啾咪小魔王
 * @date 2022/4/6 10:44
 * @since JDK 1.8
 */
@SuppressWarnings("all")
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //页面跳转
        String action = request.getParameter("action");
        if ("vcode".equals(action)) {
            VerificationCode code = new VerificationCode();
            BufferedImage image = code.getImage();
            String text = code.getText();
            HttpSession session = request.getSession();
            session.setAttribute("vcode", text);
            VerificationCode.output(image, response.getOutputStream());
        } else {
            request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Integer login = userService.login(username, password, request);
        RespBean respBean = null;
        if (login == CommonsUtils.ERROR_FORBIDDEN) {
            respBean = RespBean.respError("账户禁用，登录失败");
        } else if (login == CommonsUtils.ERROR_USER) {
            respBean = RespBean.respError("用户不存在");
        } else if (login == CommonsUtils.ERROR_PASSWORD) {
            respBean = RespBean.respError("密码错误");
        } else if (login == CommonsUtils.SUCCESS_OK) {
            respBean = RespBean.respSuccess("登录成功");
        } else if (login == CommonsUtils.ERROR_SECURITY_CODE) {
            respBean = RespBean.respError("验证码错误，请重新输入");
        } else {
            respBean = RespBean.respError("登陆失败");
        }
        response.getWriter().write(new ObjectMapper().writeValueAsString(respBean));
    }
}
